<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="76px">
        <el-form-item label="模具">
          <el-select
            style="width: 100%"
            v-model="searchParam.assetId"
            placeholder="请选择模具"
            filterable
            :filter-method="customMouldFilter"
            clearable
          >
            <el-option
              v-for="item in filteredMouldList"
              :key="item.id"
              :label="item.assetName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备">
          <el-select
            style="width: 100%"
            v-model="searchParam.equipId"
            placeholder="请选择设备"
            filterable
            :filter-method="customEquipFilter"
            clearable
          >
            <el-option
              v-for="item in filteredEquipList"
              :key="item.id"
              :label="item.equipCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="登记时间">
          <el-date-picker
            v-model="searchParam.registrationTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getregistrationTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="模具编码"
          prop="assetCode"
          min-width="230"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="模具名称"
          prop="assetName"
          min-width="200"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="设备"
          prop="equipCode"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="使用模数"
          prop="useQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
          header-align="center"
        />
        <el-table-column
          label="累计模数"
          prop="totalQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
          header-align="center"
        />
        <el-table-column
          label="数据来源"
          prop="dateSource"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <span>
              {{ useDictionary("MouldLifetimeSource", scope.row?.dateSource) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="登记时间"
          prop="registrationTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              :disabled="!!scope.row.lastId"
              @click="deleteItem(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eammouldlifetimerecord-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import {
  getMdmProcessEquipApi,
  getMdmProcessEquipApi1,
} from "@/utils/commonData";
import { debounce } from "lodash-es";

defineOptions({
  name: "EAMEAMMOULDLIFETIMERECORD",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/eammouldlifetimerecord/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  assetId: "",
  assetCode: "",
  assetName: "",
  assetTypeId: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  projectId: "",
  productId: "",
  registrationTimeSearch: [],
  registrationTimeStart: "",
  registrationTimeEnd: "",
};

const deleteParam = {
  api: "/eam/eammouldlifetimerecord/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getMouldList();
  getEquipList();
  getCAtalogList();
  getCustomerList();
  getProductList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eammouldlifetimerecord/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开模具使用寿命表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改模具使用寿命";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增模具使用寿命";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开模具使用寿命表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "模具使用寿命详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getregistrationTime(data: any) {
  if (data) {
    searchParam.value.registrationTimeStart = data[0];
    searchParam.value.registrationTimeEnd = data[1];
  } else {
    searchParam.value.registrationTimeStart = "";
    searchParam.value.registrationTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eammouldlifetimerecord/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

const mouldList = ref([]);
const filteredMouldList = ref([]);
async function getMouldList() {
  const { data } = await request({
    url: "/eam/mouldAssetInfo/getList",
    method: "post",
    data: {},
  });
  mouldList.value = data;
  filteredMouldList.value = [...data];
}
const customMouldFilter = debounce((query: any) => {
  if (!query) {
    filteredMouldList.value = [...mouldList.value];
    return;
  }
  filteredMouldList.value = mouldList.value.filter((option: any) =>
    option.assetName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);
const equipList = ref([]);
const filteredEquipList = ref([]);
async function getEquipList() {
  const { data } = await request({
    url: "/mdm/mdmequipinfo/getList",
    method: "post",
    data: {},
  });
  equipList.value = data;
  filteredEquipList.value = [...data];
}
const customEquipFilter = debounce((query: any) => {
  if (!query) {
    filteredEquipList.value = [...equipList.value];
    return;
  }
  filteredEquipList.value = equipList.value.filter((option: any) =>
    option.equipCode.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/mouldAssetType/getAvailableTree",
    method: "POST",
    data: { assetKind: "3" },
  }).then((res) => {
    catalogList.value = res.data;
  });
};
// 获取客户
const customerList: any = ref([]);
const getCustomerList = async () => {
  // 获取内容树
  await request({
    url: "/mdm/mdmprojectinfo/getList",
    method: "POST",
    data: { assetKind: "3" },
  }).then((res) => {
    customerList.value = res.data;
  });
};
// 获取项目
const productList: any = ref([]);
const getProductList = async () => {
  // 获取内容树
  await request({
    url: "/mdm/mdmmaterial/getList",
    method: "POST",
    data: { materialType: "3" },
  }).then((res) => {
    productList.value = res.data;
  });
};
</script>
